// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.parsers;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import net.web2me.api.AbstractBaseParser;
import net.web2me.api.IParser;
import net.web2me.api.ParserException;
import net.web2me.api.ParserFactory;
import net.web2me.api.ParserFactoryException;
import net.web2me.api.ProcessFinishedException;
import net.web2me.api.util.DocumentGenerator;
import net.web2me.api.util.SiteStreamGenerator;
import net.web2me.api.util.UtilityException;

/**
 * Parses a page that contains several links to ImageFap galleries.<br/>
 * Like the ones that displays after doing a search.
 * @author web2me
 *
 */
public class ImageFapBulkParser extends AbstractBaseParser {

	private final static Logger logger = Logger.getLogger(ImageFapBulkParser.class);
	private final static String IMAGEFAP_PARSER_ID = "ImageFap";
	private final static String IMAGEFAP_HOST = "http://imagefap.com/";
	private List<String> linksQueue = new ArrayList<String>();
	private boolean continueOnError = false;
	
	public boolean isContinueOnError() {
		return continueOnError;
	}

	public void setContinueOnError(boolean continueOnError) {
		this.continueOnError = continueOnError;
	}

	public static Logger getLogger() {
		return logger;
	}

	@Override
	public void process(String pageContent) throws ParserException,
			ProcessFinishedException {

		Document page = null;
			
		try {
			page = DocumentGenerator.generate(pageContent);
		} catch (Exception e) {
			getLogger().fatal("Exception caught while building the document", e);
			throw new ParserException(e);
		}
		
		IParser imageFapParser = null;
		
		try {
			imageFapParser = ParserFactory.getParser(IMAGEFAP_PARSER_ID);
		} catch (ParserFactoryException e) {
			getLogger().fatal("ParserFactoryException caught while creating the ImageFap parser", e);
			throw new ParserException(e);
		} catch (MalformedURLException e) {
			getLogger().fatal("MalformedURLException caught while creating the ImageFap parser", e);
			throw new ParserException(e);
		}
		
		NodeList links = page.getElementsByTagName("a");
		String tmpLink = "";
		String tmpHref = "";
		
		logger.info("DEBUG: Links found: " + links.getLength());
		
		for(int i = 0; i < links.getLength(); i++){
			Element link = (Element) links.item(i);
			
			logger.info("DEBUG: Link href: " + link.getAttribute("href"));
			
			if((tmpHref = link.getAttribute("href")).contains("gallery.php?gid=")){
				tmpLink = tmpHref.startsWith("http://") ? tmpHref: IMAGEFAP_HOST + tmpHref;
				tmpLink = tmpLink.endsWith("&gen=0") ? tmpLink.substring(0, tmpLink.lastIndexOf("&gen=0") - 1): tmpLink;
				getLogger().debug("Adding \"" + tmpLink + "\" to queue");
				
				linksQueue.add(tmpLink);
			}
		}
		
		if(linksQueue.size() == 0){
			throw new ParserException("No galleries links found");
		}
		
		getLogger().info("Preparing to download " + linksQueue.size() + " galleries");
		
		String content = "";
		
		for(String link: linksQueue){
			try {
				content = SiteStreamGenerator.getStream(link);
				imageFapParser.process(content);
			} catch (UtilityException e) {
				getLogger().error("UtilityException while parsing \"" + link + "\"", e);
				
				if(!isContinueOnError()){
					throw new ParserException(e);
				}
				
				continue;
			} catch(ParserException e){
				getLogger().error("ParserException caught while parsing \"" + link + "\"", e);
			
				if(!isContinueOnError()){
					throw e;
				}
			}
		}
	}

}
